package com.itcast.demo.remoterfc.httpurlconnection;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/dopost")
@Slf4j
public class HttpUrlDoPostController {
    public static String httpUrl = "...";
    public static final String httpMethod = "POST";
    public static final String basicAppToken = "";
    public static final String params = "";

    @PostMapping("/rfc")
    public void getRemoteDoPostRfc() throws Exception {
        URL url = new URL(httpUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod(httpMethod);
        connection.setRequestProperty("Authorization", basicAppToken);
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoOutput(true);
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(30000);

        HashMap<String, String> map = new HashMap<>();
        map.put("network_id", "N10667");
        String requestBody = JSON.toJSONString(map);
        try (OutputStream os = connection.getOutputStream()) {
            byte[] input = requestBody.getBytes("UTF-8");
            os.write(input, 0, input.length);
        }
        int responseCode = connection.getResponseCode();
        System.out.println("响应状态码： " + responseCode);

        if (responseCode == HttpURLConnection.HTTP_OK) {
            try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"))) {
                StringBuilder response = new StringBuilder();
                String line;
                while ((line = br.readLine()) != null) {
                    response.append(line).append("\n");
                }
                System.out.println(response.toString());
                String str = response.toString();
                Map map1 = JSON.parseObject(str, Map.class);
                int total = (int) map1.get("total");
                List<NetWorkBean> result = (List<NetWorkBean>) map1.get("result");
                Results results = new Results();
                results.setTotal(total);
                results.setList(result);

                System.out.println("==============");
                System.out.println(results);

            }
        } else {
            throw new RuntimeException();
        }
    }

}
